package com.github.bluzwang.fluxsupportkotlin;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangzhijie@wind-mobi.com on 2015/9/23.
 */
public class RemainUtils {
    public static void autoSave(Store store, SavedData savingData) {
        if (store == null || savingData == null) {
            return;
        }
        Class<? extends Store> storeClass = store.getClass();
        Field[] fields = storeClass.getDeclaredFields();
        List<String> savedNames = new ArrayList<String>();
        for (Field field : fields) {
            Remain autoSave = field.getAnnotation(Remain.class);
            if (autoSave == null) {
                continue;
            }
            String name = field.getName();
            field.setAccessible(true);
            try {
                Object value = field.get(store);
                if (value == null) {
                    continue;
                }
                savingData.put(name, value);
                savedNames.add(name);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if (savedNames.size() > 0) {
            savingData.put(""+store.getOwner(), savedNames);
        }
    }

    public static void autoRestore(Store store, SavedData savedData) {
        if (store == null || savedData == null) {
            return;
        }
        Object savedNamesTmp = savedData.get("" + savedData.getOwnerHashCode());
        if (savedNamesTmp == null || !(savedNamesTmp instanceof List)) {
            return;
        }
        Class<? extends Store> storeClass = store.getClass();
        Field[] fields = storeClass.getDeclaredFields();
        List<String> savedNames = (List<String>) savedNamesTmp;
        for (String name : savedNames) {
            Object obj = savedData.get(name);
            if (obj == null) {
                continue;
            }
            for (Field field : fields) {
                if (field.getName().equals(name)) {
                    field.setAccessible(true);
                    try {
                        field.set(store, obj);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
